﻿package com.firewolf.zip.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 压缩解压工具类
 * 
 * @author Administrator
 *
 */
public class ZipUtil {
	/**
	 * 压缩文件
	 * 
	 * @param files
	 *            ： 要压缩的文件数组
	 * @param location
	 *            ： 压缩后放置的位置
	 * @param fileName
	 *            ： 压缩后的文件名
	 * @throws IOException
	 */
	public static void pressFiles(File[] files, String location, String fileName)
			throws IOException {
		ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(
				new File(fileName)));
		byte[] buf = new byte[1024];
		for (File file : files) {
			FileInputStream in = new FileInputStream(file);
			zout.putNextEntry(new ZipEntry(file.getName()));
			int length = 0;
			while ((length = in.read(buf)) != -1) {
				zout.write(buf, 0, length);
			}
			in.close();
			zout.closeEntry();
		}
		zout.close();
	}

	/**
	 * 解压文件
	 * 
	 * @param zipFile
	 *            ：要解压的文件
	 * @throws IOException
	 */
	public static void unpressZipFile(File zipFile) throws IOException {
		System.out.println("开始解压文件");
		ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
		ZipEntry entry;
		while ((entry = zin.getNextEntry()) != null) {
			String fileName = entry.getName();
			FileWriter fWriter = new FileWriter(new File(zipFile.getParent()
					+ "\\" + fileName));
			Scanner in = new Scanner(zin);
			while (in.hasNextLine()) {
				fWriter.write(in.nextLine() + "\n");
			}
			fWriter.close();
			zin.closeEntry();
		}
		zin.close();
	}
}
